package org.example.controller;

import org.example.mapper.UserDaoMapper;
import org.example.mapper.UserMapper;
import org.example.model.data.UserData;
import org.example.model.dto.UserRegistrationRequest;
import org.example.model.entity.User;
import org.example.response.ApiResponse;
import org.example.service.UserService;
import org.example.util.SnowflakeIdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.example.util.KeyUtil;
@RestController
@RequestMapping("/api/registration")
public class RegistrationController {

    private final UserService userService;
    private final UserDaoMapper userDaoMapper;
    private final RedisTemplate redisTemplate;
@Autowired
    public RegistrationController(UserService userService,  UserDaoMapper userDaoMapper, RedisTemplate redisTemplate) {
    this.userService = userService;
    this.userDaoMapper = userDaoMapper;
    this.redisTemplate = redisTemplate;

    }
@RequestMapping("/register")
    public ApiResponse<UserData> register(@RequestBody UserRegistrationRequest registrationRequest) {

        try {
            // 参数验证
            validateRegistrationRequest(registrationRequest);

            // 检查验证码
            if (!isValidCaptcha(registrationRequest.getEmail(), registrationRequest.getCode())) {
                System.out.println("错误邮箱：" + registrationRequest.getEmail());
                System.out.println("错误验证码：" + registrationRequest.getCode());
                return ApiResponse.error("验证码错误！");
            }

//            // 检查用户名和手机号码是否已存在
//            if (userService.isExistsByUsername(registrationRequest.getUserName())) {
//                return ApiResponse.error("用户名已存在！");
//            }
//            if (userService.isExistsByPhone(registrationRequest.getPhone())) {
//                return ApiResponse.error("手机号码已存在！");
//            }

            // 创建用户对象并设置属性
            User user = new User();
            user.setId(generateUniqueId());
           // user.setUserName(registrationRequest.getUserName());
            user.setUserName(generateUniqueId());
            user.setEmail(registrationRequest.getEmail());
            //user.setPhone(registrationRequest.getPhone());
            user.setPassword(KeyUtil.Md5(registrationRequest.getPassword())); // 加密密码

            // 保存用户
            if (userService.save(user)) {
                UserData userData = userDaoMapper.selectById(user.getId());
                return ApiResponse.success(userData);
            } else {
                return ApiResponse.error("创建失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }

    private String generateUniqueId() {
        return String.valueOf(new SnowflakeIdGenerator(20, 21).nextId());
    }

    private boolean isValidCaptcha(String email, String code) {
        String cachedCode = (String) redisTemplate.opsForValue().get("captcha:" + email);
        System.out.println("cachedCode:" + cachedCode);
        return code != null && code.equals(cachedCode);
    }

    private void validateRegistrationRequest(UserRegistrationRequest request) {
        if (request == null ||
               // StringUtils.isEmpty(request.getUserName()) ||
                StringUtils.isEmpty(request.getEmail()) ||
                //StringUtils.isEmpty(request.getPhone()) ||
                StringUtils.isEmpty(request.getPassword()) ||
                StringUtils.isEmpty(request.getCode())) {
            throw new IllegalArgumentException("信息不完整！");
        }
    }
}
